package edu.mju.security.entity;

import lombok.Data;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * 用户信息 实现UserDetails接口
 */
@Data
public class SecurityUser implements UserDetails {


    /**
     * transient：该对象不被序列号 ，当前登录对象
     */
    private transient Users users;

    /**
     * 当前权限
     */
    private List<String> permissionList;

    public SecurityUser() {
    }

    public SecurityUser(Users users) {
        if(!ObjectUtils.isEmpty(users)){
            this.users = users;
        }
    }

    /**
     * 用户权限列表遍历
     * @return 返回用户权限列表集合
     */
    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        Collection<GrantedAuthority> authorities = new ArrayList<>();
        for (String permissionValue : permissionList) {
            if (StringUtils.isEmpty(permissionValue)) {
                continue;
            }
            SimpleGrantedAuthority authority = new SimpleGrantedAuthority(permissionValue);
            authorities.add(authority);
        }

        return authorities;
    }

    @Override
    public String getPassword() {
        return users.getPassword();
    }

    @Override
    public String getUsername() {
        return users.getUsername();
    }

    /**
     * 用户账户有效期 默认一直未过期
     */
    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    /**
     * 账户是否被锁 默认未被锁
     */
    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    /**
     * 用户密码有效期 默认一直未过期
     */
    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    /**
     * 用户是否被禁用 默认启用
     */
    @Override
    public boolean isEnabled() {
        return true;
    }
}
